package cool.tianyou.blue.bird.util;

import android.content.Context;
import android.os.Build;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.zxing.common.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import cool.tianyou.blue.bird.constant.Constant;
import cool.tianyou.blue.bird.model.ApiResult;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void post(Context context, Object data, String url, Consumer<ApiResult<?>> success) {
        String body = data == null ? "{}" : JSONObject.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect);
        RequestBody requestBody = RequestBody.create(Constant.MEDIA_TYPE_JSON, body);
        final Request request = new Request.Builder().url("http://" + Constant.DOMAIN + url).post(requestBody)
                .addHeader("Authorization", Constant.USER_INFO.TOKEN)
                .build();
        final OkHttpClient client = createHttpClient();
        new Thread(() -> {
            try {
                Response response = client.newCall(request).execute();//发送请求
                assert response.body() != null;
                String result = response.body().string();
                Log.d("请求返回", result);
                ApiResult<?> apiResult = JSONObject.parseObject(result, ApiResult.class);
                if (apiResult.getCode() == 401) {
                    Looper.prepare();
                    Util.showToast(context, "需要重新登录");
                    Util.toLogin(context);
                    return;
                }
                success.accept(apiResult);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void delete(Context context, Object data, String url, Consumer<ApiResult<?>> success) {
        String body = data == null ? "{}" : JSONObject.toJSONString(data);
        RequestBody requestBody = RequestBody.create(Constant.MEDIA_TYPE_JSON, body);
        final Request request = new Request.Builder().url("http://" + Constant.DOMAIN + url).delete(requestBody)
                .addHeader("Authorization", Constant.USER_INFO.TOKEN)
                .build();
        final OkHttpClient client = createHttpClient();
        new Thread(() -> {
            try {
                Response response = client.newCall(request).execute();//发送请求
                assert response.body() != null;
                String result = response.body().string();
                Log.d("请求返回", result);
                ApiResult<?> apiResult = JSONObject.parseObject(result, ApiResult.class);
                if (apiResult.getCode() == 401) {
                    Looper.prepare();
                    Util.showToast(context, "需要重新登录");
                    Util.toLogin(context);
                    return;
                }
                success.accept(apiResult);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void put(Context context, Object data, String url, Consumer<ApiResult<?>> success) {
        String body = data == null ? "{}" : JSONObject.toJSONString(data);
        RequestBody requestBody = RequestBody.create(Constant.MEDIA_TYPE_JSON, body);
        final Request request = new Request.Builder().url("http://" + Constant.DOMAIN + url).put(requestBody)
                .addHeader("Authorization", Constant.USER_INFO.TOKEN)
                .build();
        final OkHttpClient client = createHttpClient();
        new Thread(() -> {
            try {
                Response response = client.newCall(request).execute();//发送请求
                assert response.body() != null;
                String result = response.body().string();
                Log.d("请求返回", result);
                ApiResult<?> apiResult = JSONObject.parseObject(result, ApiResult.class);
                if (apiResult.getCode() == 401) {
                    Looper.prepare();
                    Util.showToast(context, "需要重新登录");
                    Util.toLogin(context);
                    return;
                }
                success.accept(apiResult);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void get(Context context, Object data, String url, Consumer<ApiResult<?>> success) {
        final Request request = new Request.Builder().url("http://" + Constant.DOMAIN + url + object2urlParam(data)).get()
                .addHeader("Authorization", Constant.USER_INFO.TOKEN)
                .build();
        final OkHttpClient client = createHttpClient();
        new Thread(() -> {
            try {
                Response response = client.newCall(request).execute();//发送请求
                assert response.body() != null;
                String result = response.body().string();
                Log.d("请求返回", result);
                ApiResult<?> apiResult = JSONObject.parseObject(result, ApiResult.class);
                if (apiResult.getCode() == 401) {
                    Looper.prepare();
                    Util.showToast(context, "需要重新登录");
                    Util.toLogin(context);
                    return;
                }
                success.accept(apiResult);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    private static String object2urlParam(Object data) {
        if (data == null) {
            return "";
        }
        HashMap<String, Object> hashMap = JSON.parseObject(JSON.toJSONString(data), HashMap.class);
        String param = hashMap.entrySet().stream()
                .filter(entry -> entry.getValue() != null)
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        if (param.length() > 0) {
            return "?" + param;
        }
        return "";
    }


    private static OkHttpClient createHttpClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS).build();
        return client;
    }

}
